<script setup>
import { ref, onMounted } from 'vue';
//导入dept.js中的queryAllApi方法
import { queryAllApi, addDeptApi, queryByIdApi, updateDeptApi, deleteDeptApi } from '@/api/dept'
import { ElMessage, ElDialog, ElMessageBox } from 'element-plus';
// 模拟数据
const tableData = ref([]);

const dialogVisible = ref(false); // 控制对话框的显示与隐藏
const newDepartment = ref({ name: '', updateTime: '' }); // 用于存储新部门的信息
const deptForm = ref(null); // 用于绑定表单实例

// 定义校验规则
const rules = {
  name: [
    { required: true, message: '部门名称不能为空', trigger: 'blur' },
    { min: 2, max: 20, message: '部门名称长度在 2 到 20 个字符之间', trigger: 'blur' }
  ],
  updateTime: [
    { required: true, message: '最后修改时间不能为空', trigger: 'blur' }
  ]
};


const dialogTitle = ref('');

// 重置表单
const resetForm = () => {
  deptForm.value.resetFields()
}


// 查询部门数据
const fetchDepartments = async () => {

  const result = await queryAllApi();

  if (result.code) {//不用再加data,因为request 已经做了处理
    tableData.value = result.data; // 将获取的数据绑定到 tableData
  } else {
    ElMessage.error(result.msg);
  }
};

// 组件挂载时自动加载数据
onMounted(() => {
  fetchDepartments();
});

// 处理修改操作
// 编辑部门 - 根据ID查询回显数据
const handleEdit = async (id) => {
  console.log(`Edit item with ID ${id}`);

  dialogTitle.value = '修改部门';

  //弹出对话框
  dialogVisible.value = true;

  const result = await queryByIdApi(id);
  if (result.code) {
    newDepartment.value = result.data;// 回显数据到表单
  }

};

// 处理删除操作
const handleDelete = async (id) => {
  console.log(`Delete item with ID ${id}`);
  try {
    //删除部门时, 需要弹出一个确认框, 如果是确认, 则删除部门
    await ElMessageBox.confirm('此操作将永久删除该部门, 是否继续?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const result = await deleteDeptApi(id);
    if (result.code) {
      ElMessage.success('删除成功');
      fetchDepartments();
    } else {
      //如果部门下有员工 则不能删除
      ElMessage.error(result.msg);
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + error.message);
    }
  }
};


// 处理添加部门操作
const handleAdd = () => {
  dialogTitle.value = '添加部门';
  dialogVisible.value = true; // 显示对话框
  //清空表单
  newDepartment.value = { name: '', updateTime: '' };

};

// 提交新部门
const submitDepartment = async () => {
  // 先进行表单校验
  await deptForm.value.validate(async (valid) => {
    if (!valid) return;
    // 校验通过，提交数据
    //const result = await addDeptApi(newDepartment.value)



    let result;
    if (dialogTitle.value === '添加部门') {
      result = await addDeptApi(newDepartment.value); // 添加部门
    } else {
      result = await updateDeptApi(newDepartment.value); // 修改部门
    }

    if (result.code) {
      ElMessage.success('操作成功')
      // 关闭对话框
      dialogVisible.value = false; // 提交后关闭对话框
      // 重置表单
      resetForm()
      // 重新加载数据
      fetchDepartments();
    } else {
      ElMessage.error(result.msg)
    }
  });
};

</script>

<template>
  <h1>部门管理</h1>

  <br>

  <el-button type="primary" @click="handleAdd">添加部门</el-button>
  <br><br>

  <el-table :data="tableData" border style="width: 100%">
    <el-table-column type="index" label="序号" width="120" align="center"></el-table-column>
    <el-table-column prop="name" label="部门名称" width="320" align="center"></el-table-column>
    <el-table-column prop="updateTime" label="最后修改时间" width="400" align="center"></el-table-column>
    <el-table-column label="操作" align="center">
      <template #default="scope">
        <el-button type="primary" size="small" @click="handleEdit(scope.row.id)">修改</el-button>
        <el-button type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>


  <!-- 添加部门的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
    <el-form :model="newDepartment" :rules="rules" ref="deptForm" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="newDepartment.name"></el-input>
      </el-form-item>
      <el-form-item label="最后修改时间">
        <el-input v-model="newDepartment.updateTime"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitDepartment">提交</el-button>
    </template>
  </el-dialog>






</template>

<style scoped></style>
